<?php
namespace app\api\service;

class MyAES{
    /**
     * 加密方法
     * @param string $str
     * @return string
     */
    public function encrypt($str, $key){
        $screct_key = $key;
        //$screct_key = base64_decode($screct_key);
        $str = trim($str);
        $str = $this->addPKCS7Padding($str,$screct_key);

        return base64_encode($str);
    }

    /**
     * 解密方法
     * @param string $str
     * @return string
     */
    public function decrypt($str, $key){
        $screct_key = $key;
        $str = base64_decode($str);
        //$screct_key = base64_decode($screct_key);
        $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128,MCRYPT_MODE_ECB),MCRYPT_RAND);
        $encrypt_str =  mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $screct_key, $str, MCRYPT_MODE_ECB, $iv);
        //$encrypt_str = trim($encrypt_str);
        $encrypt_str = $this->stripPKSC7Padding($encrypt_str);
        return $encrypt_str;
    }
    public function PKCS7Padding($str, $block_size) {
        $padding_char = $block_size - (strlen($str) % $block_size);
        $padding_str = str_repeat(chr($padding_char),$padding_char);
        return $str.$padding_str;
    }
    /**
     * 填充算法
     * @param string $source
     * @return string
     */
    public function addPKCS7Padding($source,$key){
//        $source = trim($source);
//        $block = mcrypt_get_block_size('rijndael-128', 'ecb');
//        $pad = $block - (strlen($source) % $block);
//        if ($pad <= $block) {
//            $char = chr($pad);
//            $source .= str_repeat($char, $pad);
//        }
        $ivlen = openssl_cipher_iv_length('AES-128-CBC');
        $iv = openssl_random_pseudo_bytes($ivlen);
        $source = $this->PKCS7Padding($source, 16);
        $encrypted = openssl_encrypt($source, 'AES-128-CBC', $key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $iv);
        $source = base64_encode($encrypted);
        return $source;
    }
    /**
     * 移去填充算法
     * @param string $source
     * @return string
     */
    public function stripPKSC7Padding($source){
        $char=substr($source,-1,1);
        $num=ord($char);
        if($num>0 && $num <= strlen($source)) {
            $source = substr($source, 0, -1 * $num);
        }
        return $source;
    }

}
